package com.os.opencv.java.chapter8;

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.ArrayList;
import java.util.List;

public class CalcHist {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/msk.jpg");
        HighGui.imshow("src", src);
        HighGui.waitKey(0);

        //参数准备
        List<Mat> mat = new ArrayList<>();
        mat.add(src);
        float[] range = {0, 256};  //直方图的统计范围
        Mat hist = new Mat();
        MatOfFloat histRange = new MatOfFloat(range);

        //直方图数据统计并归一化
        Imgproc.calcHist(mat, new MatOfInt(0), new Mat(), hist, new MatOfInt(256), histRange);
        int width = 512, height = 400;  //直方图图像尺寸
        Core.normalize(hist, hist, 0, height, Core.NORM_MINMAX);

        //将直方图数据转存到数组中以便后续使用
        float[] histData = new float[(int) (hist.total() * hist.channels())];
        hist.get(0,0,histData);

        //绘制直方图
        Scalar black = new Scalar(0,0,0);
        Scalar white = new Scalar(255,255,255);
        Mat histImage = new Mat(height, width, CvType.CV_8UC3, black);

        int binWid = (int)Math.round((double) width/256);
        //bin宽度
        for(int i=0; i<256; i++){
            Imgproc.line(histImage, new Point(i*binWid, height), new Point(i*binWid, height-Math.round(histData[i])),
                    white, binWid);
        }

        //在屏幕上显示绘制的直方图
        HighGui.imshow("calcHist", histImage);
        HighGui.waitKey(0);

        System.exit(0);
    }
}
